//
//  MTContractDetailViewController.m
//  ERP
//
//  Created by goldeney on 15/4/20.
//  Copyright (c) 2015年 ShangHai Goldeneye Techonology Co.,Ltd. All rights reserved.
//

#import "MTCContractDetailViewController.h"

#import "AutoTextTableViewCell.h"
#import "TableOneButtonViewCell.h"
#import "NSDictionary+DataFormat.h"

#import "NSString+handle.h"
#import "NSKeyedArchiverUserLogin.h"
#import "RKTabView.h"
#import "BGRadioView.h"

#import "Charts-Swift.h"
#import "PNChart.h"
#import "JGActionSheet.h"
#import "WebServiceCommonRequest.h"
#import "MTCContractDetailViewCell.h"

#import "MTCRWDLogisticsInfoViewController.h"
#import "MTCConcretePriceViewController.h"
#import "MTCPumpPriceViewController.h"
#import "MTCAlreadyAddConcreteViewController.h"
#import "MTCContractRWDListViewController.h"
#import "MTCCreateContractViewController.h"
#import "MTCContractProjectViewController.h"
#import "MTCCreateContractTYDZController.h"

@interface MTCContractDetailViewController ()

@property (nonatomic,strong) NSDictionary *orderInfo;
@property (nonatomic,strong) NSMutableArray *concreteArray;
@property (nonatomic,strong) NSMutableArray *auditArray;
@property (nonatomic,strong) NSMutableArray *operateArray;
@property (nonatomic,strong) NSMutableArray *functionArray;

@property (nonatomic,strong) NSString *orderID;
@property (nonatomic,assign) BOOL isNetworkOrder;

@property (nonatomic,assign) BOOL isShowSQ_FF_XZ;
@property (nonatomic,assign) BOOL isShowSH_BJ;
@property (nonatomic,assign) BOOL isAllowOperate;

@end

@implementation MTCContractDetailViewController
@synthesize tableView = _tableView;
@synthesize concreteArray,auditArray,operateArray;

- (id)initWithModel:(NSDictionary*)model
{
    self = [super init];
    if (self) {
        [self setTitle: @"合同明细"];
        self.orderInfo = [NSMutableDictionary dictionaryWithDictionary:model];
        self.isAllowOperate = YES;
    }
    return self;
}

- (id)initWithModel:(NSDictionary*)model isAllowOperate:(BOOL)isAllowOperate
{
    self = [super init];
    if (self) {
        [self setTitle: @"合同明细"];
        self.orderInfo = [NSMutableDictionary dictionaryWithDictionary:model];
        self.isAllowOperate = isAllowOperate;
    }
    return self;
}

- (void)addContractInfoKey:(id)key toKey:(id)tokey defaults:(id)def format:(id)formatText
                      form:(NSDictionary*)dic toArray:(NSMutableArray*)array
{
    id value = [dic objectFormatForKey:key];
    if (!def) def = @"";
    
    if (!value){
        value = def;
    } else if (formatText) {
        value = [NSString stringWithFormat:formatText,value];
    }
    
    NSDictionary *valueDic = [NSDictionary dictionaryWithObject:value forKey:tokey];
    [array addObject:valueDic];
}

#pragma mark 权限配置

- (void)menuAuthorityConfiguration:(NSDictionary*)dic
{
    //合同授权、分发、新增权限设置
    BOOL HTSQ = [ModuleAuthorityEntity MR_findByAttribute:@"permissionsMark" withValue:@"P_HTGL_HTSQ"].count;
    BOOL HTFF = [ModuleAuthorityEntity MR_findByAttribute:@"permissionsMark" withValue:@"P_HTGL_HTFF"].count;
    BOOL HTXZ = [ModuleAuthorityEntity MR_findByAttribute:@"permissionsMark" withValue:@"P_HTGL_HTXZ"].count;
    if(HTSQ || HTFF || HTXZ) self.isShowSQ_FF_XZ = YES;
    
    //合同审核、编辑权限设置
    BOOL HTSH = [ModuleAuthorityEntity MR_findByAttribute:@"permissionsMark" withValue:@"P_HTGL_HTSH"].count;
    BOOL HTBJ = [ModuleAuthorityEntity MR_findByAttribute:@"permissionsMark" withValue:@"P_HTGL_HTBJ"].count;
    if(HTSH || HTBJ) self.isShowSH_BJ = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self menuAuthorityConfiguration:self.orderInfo];
    [self getOrderAllOrders:self.orderInfo];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)getOrderAllOrders:(NSDictionary*)dic
{
    self.concreteArray = [NSMutableArray array];
    [self addContractInfoKey:@"合同编号" toKey:@"合同编号：" defaults:@"未知" format:nil form:dic toArray:concreteArray];
    [self addContractInfoKey:@"合同名称" toKey:@"合同名称：" defaults:@"未知" format:nil form:dic toArray:concreteArray];
    [self addContractInfoKey:@"客户名称" toKey:@"客户名称：" defaults:@"未知" format:nil form:dic toArray:concreteArray];
    [self addContractInfoKey:@"施工单位" toKey:@"施工单位：" defaults:@"未知" format:nil form:dic toArray:concreteArray];
    [self addContractInfoKey:@"建设单位" toKey:@"建设单位：" defaults:@"未知" format:nil form:dic toArray:concreteArray];
    [self addContractInfoKey:@"第三方单位" toKey:@"第三方单位：" defaults:@"无" format:nil form:dic toArray:concreteArray];
    [self addContractInfoKey:@"工地地址" toKey:@"工地地址：" defaults:@"未知" format:nil form:dic toArray:concreteArray];
    [self addContractInfoKey:@"制表人员" toKey:@"制表人员：" defaults:@"未知" format:nil form:dic toArray:concreteArray];
    [self addContractInfoKey:@"制表日期" toKey:@"制表日期：" defaults:@"未知" format:nil form:dic toArray:concreteArray];
    [self addContractInfoKey:@"备注" toKey:@"备        注：" defaults:@"无" format:nil form:dic toArray:concreteArray];
    
    self.auditArray = [NSMutableArray array];
    [self addContractInfoKey:@"审核状态" toKey:@"审核状态：" defaults:@"未知" format:nil form:dic toArray:auditArray];
    [self addContractInfoKey:@"合同性质" toKey:@"合同性质：" defaults:@"未知" format:nil form:dic toArray:auditArray];
    [self addContractInfoKey:@"签订方量" toKey:@"签订方量：" defaults:@"未知" format:@"%@方" form:dic toArray:auditArray];
    [self addContractInfoKey:@"追加方量" toKey:@"追加方量：" defaults:@"未知" format:@"%@方" form:dic toArray:auditArray];
    [self addContractInfoKey:@"是否控制方量" toKey:@"是否方量控制：" defaults:@"未知" format:nil form:dic toArray:auditArray];
    [self addContractInfoKey:@"运输距离" toKey:@"运输距离：" defaults:@"未知" format:@"%@公里" form:dic toArray:auditArray];
    [self addContractInfoKey:@"签订日期" toKey:@"签订日期：" defaults:@"未知" format:nil form:dic toArray:auditArray];
    [self addContractInfoKey:@"业务人员" toKey:@"业务人员：" defaults:@"未知" format:nil form:dic toArray:auditArray];
    [self addContractInfoKey:@"业务员电话" toKey:@"业务员电话：" defaults:@"未知" format:nil form:dic toArray:auditArray];
    [self addContractInfoKey:@"工地联系人" toKey:@"工地联系人：" defaults:@"未知" format:nil form:dic toArray:auditArray];
    [self addContractInfoKey:@"工地联系电话" toKey:@"工地联系电话：" defaults:@"未知" format:nil form:dic toArray:auditArray];
    
    self.operateArray = [NSMutableArray array];
    [self addContractInfoKey:@"合同状态" toKey:@"合同状态：" defaults:@"未知" format:nil form:dic toArray:operateArray];
    [self addContractInfoKey:@"分发站点" toKey:@"分发站点：" defaults:@"未知" format:nil form:dic toArray:operateArray];
    [self addContractInfoKey:@"分发状态" toKey:@"分发状态：" defaults:@"未知" format:nil form:dic toArray:operateArray];
    
    
    self.functionArray = [NSMutableArray array];
    [self.functionArray addObject:@[@"合同工程",@"合同工程新增编辑",@0]];
    [self.functionArray addObject:@[@"方量追加",@"合同追加方量信息",@0]];
    [self.functionArray addObject:@[@"砼价格",@"各个日期阶段砼价格",@0]];
    
}

- (PieChartData*)setDataArray:(NSDictionary*)dictionary
{
    CGFloat htzl = [[dictionary objectFormatFloatNumberForKey:@"合同总量"] floatValue];
    CGFloat ywcl = [[dictionary objectFormatFloatNumberForKey:@"已完成量"] floatValue];
    CGFloat syl = htzl - ywcl;
    
    NSMutableArray *yVals1 = [[NSMutableArray alloc] init];
    if(syl>0){
        [yVals1 addObject:[[PieChartDataEntry alloc] initWithValue:(htzl!=0?ywcl/htzl*100:0) label:@"完成量"]];
        [yVals1 addObject:[[PieChartDataEntry alloc] initWithValue:(htzl!=0?syl/htzl*100:0) label:@"剩余量"]];
    } else {
        [yVals1 addObject:[[PieChartDataEntry alloc] initWithValue:100 label:@"完成量"]];
        [yVals1 addObject:[[PieChartDataEntry alloc] initWithValue:0 label:@"剩余量"]];
        //[colors addObject:ThemeColorGreen];
        //[colors addObject:[UIColor colorWithRed:255/255.f green:99/255.f blue:71/255.f alpha:1.f]];
    }

    NSString *htzt = [NSString stringWithFormat:@"合同%@",[dictionary objectFormatStringForKey:@"合同状态"]];
    PieChartDataSet *dataSet = [[PieChartDataSet alloc] initWithValues:yVals1 label:htzt];
    dataSet.sliceSpace = 3.f;
    
    // add a lot of colors
    NSMutableArray *colors = [[NSMutableArray alloc] init];
    [colors addObject:ThemeColorGreen];
    [colors addObject:[UIColor colorWithRed:170/255.0 green:170/255.0 blue:170/255.0 alpha:1]];
    dataSet.colors = colors;
    
    //PieChartData *data = [[PieChartData alloc] initWithXVals:xVals dataSet:dataSet];
    PieChartData *data = [[PieChartData alloc] initWithDataSet:dataSet];
    NSNumberFormatter *pFormatter = [[NSNumberFormatter alloc] init];
    pFormatter.numberStyle = NSNumberFormatterPercentStyle;
    pFormatter.maximumFractionDigits = 1;
    pFormatter.multiplier = @1.f;
    pFormatter.percentSymbol = @" %";
    //[data setValueFormatter:pFormatter];
    [data setValueFormatter:[[ChartDefaultValueFormatter alloc] initWithFormatter:pFormatter]];
    [data setValueFont:[UIFont fontWithName:@"HelveticaNeue-Light" size:11.f]];
    [data setValueTextColor:UIColor.whiteColor];
    
    return data;
}


#pragma mark - 合同进度分析图

- (UITableViewCell*)drawContractPlanChart
{
    NSString *htmc = [self.orderInfo objectFormatStringForKey:@"合同名称"];
    NSString *htzl = [self.orderInfo objectFormatFloatStringForKey:@"合同总量" retain:1 format:@"%@m³"];
    NSString *ywcl = [self.orderInfo objectFormatFloatStringForKey:@"已完成量" retain:1 format:@"%@m³"];
    NSString *shzt = [self.orderInfo objectFormatStringForKey:@"审核状态"];
    NSString *sfsq = [self.orderInfo objectFormatStringForKey:@"合同状态"];
    
    MTCContractDetailViewCell *childCell = [[MTCContractDetailViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MTCContractDetailViewCell"];
    childCell.selectionStyle = UITableViewCellSelectionStyleNone;
    childCell.htmcLabel.text = htmc;
    childCell.htzlLabel.text = htzl;
    childCell.ywclLabel.text = ywcl;
    childCell.shztLabel.text = shzt;
    childCell.sfsqLabel.text = sfsq;
    
    PieChartView *_chartView = [[PieChartView alloc] initWithFrame:CGRectMake(0, -10, SuperWidth - 135, 215)];
    _chartView.usePercentValuesEnabled = YES;
    _chartView.holeRadiusPercent = 0.43f;
    _chartView.transparentCircleRadiusPercent = 0.47f;
//    _chartView.descriptionText = @"";
    _chartView.drawCenterTextEnabled = YES;
    _chartView.drawHoleEnabled = YES;
    _chartView.rotationAngle = 0.f;
    _chartView.rotationEnabled = YES;
    _chartView.userInteractionEnabled = NO;
    _chartView.centerText = @"完成进度";
    
    ChartLegend *l = _chartView.legend;
    l.horizontalAlignment = ChartLegendHorizontalAlignmentRight;
    l.verticalAlignment = ChartLegendVerticalAlignmentTop;
    l.orientation = ChartLegendOrientationVertical;
    //l.xEntrySpace = 10.f;
    l.yEntrySpace = 5.f;
    l.enabled = NO;
    
    _chartView.data = [self setDataArray:self.orderInfo];
    [_chartView highlightValues:nil];
    [_chartView animateWithXAxisDuration:1.5 yAxisDuration:1.5 easingOption:ChartEasingOptionEaseOutBack];
    [childCell.chartView addSubview:_chartView];
    
    return childCell;
}

#pragma mark
#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
//    if (self.functionArray.count > 0) return 3;
//    else
    return 5;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 3){ //合同状况
        if (self.isShowSQ_FF_XZ && self.isAllowOperate) return 2;
        else return 1;
        
    } else if (section == 2) { //审核操作
        CGFloat SHZT = [self.orderInfo objectFormatFloatForKey:@"Confirm"];//审核状态
        CGFloat FFZT = [self.orderInfo objectFormatFloatForKey:@"FFZT"];//分发状态
        if (SHZT <=1 && FFZT > 0 && self.isShowSH_BJ && self.isAllowOperate) return 2;
        else return 1;
    }
    
    if(section == 4){//更多操作
        return self.functionArray.count;
    }
    
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //合同状况
    if (indexPath.section == 0 && indexPath.row == 0){
//        UITableViewCell *cell = cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TableSampleIdentifier2"];
//        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return [self drawContractPlanChart];
//        return cell;
    }
    
    //合同基本信息
    if (indexPath.section == 1 && indexPath.row == 0) {
        NSString *identifier = [NSString stringWithFormat:@"OrderInfoTableViewCell%ld",(long)indexPath.section];
        AutoTextTableViewCell *cell = [[AutoTextTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell setDataArray:concreteArray];
        return cell;
    }
    
    //审核操作
    if (indexPath.section == 2 && indexPath.row == 1) {
        static NSString *TableSampleIdentifier = @"TableSampleIdentifier";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: TableSampleIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TableSampleIdentifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.frame = CGRectMake(0, 0, SuperWidth, 48);
        }
        
        //选项卡
        NSMutableArray *tabItems = [NSMutableArray array];
        
        //审核按钮设置
        NSArray *mainMenuArray = [ModuleAuthorityEntity MR_findByAttribute:@"permissionsMark" withValue:@"P_HTGL_HTSH"];
        if (mainMenuArray.count>0){
            RKTabItem *tabItem1 = [RKTabItem createUsualItemWithImageEnabled:nil imageDisabled:[UIImage imageNamed:@"message_keyboard_background_highlighted"]];
            tabItem1.titleString = @"审核";
            tabItem1.titleFont = [UIFont systemFontOfSize:12];
            [tabItem1 addTarget:self selector:@selector(checkSelector:)];
            [tabItems addObject:tabItem1];
        } else {
            RKTabItem *tabItem1 = [RKTabItem createUsualItemWithImageEnabled:nil imageDisabled:[UIImage imageNamed:@"message_keyboard_background"]];
            tabItem1.titleString = @"审核";
            tabItem1.titleFont = [UIFont systemFontOfSize:12];
            [tabItems addObject:tabItem1];
        }
        
        //编辑按钮设置（修改，删除）
        NSArray *mainMenuArray1 = [ModuleAuthorityEntity MR_findByAttribute:@"permissionsMark" withValue:@"P_HTGL_HTBJ"];
        if (mainMenuArray1.count>0){
            RKTabItem *tabItem2 = [RKTabItem createUsualItemWithImageEnabled:nil imageDisabled:[UIImage imageNamed:@"navigationbar_compose_highlighted"]];
            tabItem2.titleString = @"修改";
            tabItem2.titleFont = [UIFont systemFontOfSize:12];
            [tabItem2 addTarget:self selector:@selector(modifySelector:)];
            [tabItems addObject:tabItem2];
            
        } else {
            RKTabItem *tabItem2 = [RKTabItem createUsualItemWithImageEnabled:nil imageDisabled:[UIImage imageNamed:@"navigationbar_compose_disable"]];
            tabItem2.titleString = @"修改";
            tabItem2.titleFont = [UIFont systemFontOfSize:12];
            [tabItems addObject:tabItem2];
            
            RKTabItem *tabItem3 = [RKTabItem createUsualItemWithImageEnabled:nil imageDisabled:[UIImage imageNamed:@"toolbar_stop"]];
            tabItem3.titleString = @"删除";
            tabItem3.titleFont = [UIFont systemFontOfSize:12];
            [tabItems addObject:tabItem3];
        }
        
        RKTabView *titledTabsView = [[RKTabView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 48)];
        titledTabsView.titlesFontColor = [UIColor grayColor];
        titledTabsView.tabItems = tabItems;
        titledTabsView.drawSplitLine = YES;
        titledTabsView.backgroundColor = [UIColor whiteColor];
        [cell.contentView addSubview:titledTabsView];
        
        //添加分割线
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 0.5)];
        lineView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.1];
        [cell.contentView addSubview:lineView];
        
        return cell;
    }
    
    //授权和新增操作
    if (indexPath.section == 3 && indexPath.row == 1){
        static NSString *TableSampleIdentifier = @"TableSampleIdentifier1";
        UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TableSampleIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        CGFloat HTZT = [[self.orderInfo objectFormatFloatNumberForKey:@"Status"] floatValue];//合同状态
        CGFloat FFZT = [[self.orderInfo objectFormatFloatNumberForKey:@"FFZT"] floatValue];//分发状态
        NSMutableArray *tabItems = [NSMutableArray array];//选项卡
        
        //授权、终止按钮
        NSArray *mainMenuArray = [ModuleAuthorityEntity MR_findByAttribute:@"permissionsMark" withValue:@"P_HTGL_HTSQ"];
        if (mainMenuArray.count>0){
            RKTabItem *tabItem1 = [RKTabItem createUsualItemWithImageEnabled:nil imageDisabled:[UIImage imageNamed:@"toolbar_favorite_highlighted"]];
            if(HTZT == 1 || HTZT == 3) tabItem1.titleString = @"启用";
            else tabItem1.titleString = @"停用";
            tabItem1.titleFont = [UIFont systemFontOfSize:12];
            [tabItem1 addTarget:self selector:@selector(accreditSelector:)];
            [tabItems addObject:tabItem1];
        } else {
            RKTabItem *tabItem1 = [RKTabItem createUsualItemWithImageEnabled:nil imageDisabled:[UIImage imageNamed:@"toolbar_favorite"]];
            if(HTZT == 1 || HTZT == 3) tabItem1.titleString = @"启用";
            else tabItem1.titleString = @"停用";
            tabItem1.titleFont = [UIFont systemFontOfSize:12];
            [tabItems addObject:tabItem1];
        }
        
        //新增按钮
        NSArray *mainMenuArray1 = [ModuleAuthorityEntity MR_findByAttribute:@"permissionsMark" withValue:@"P_HTGL_HTXZ"];
        if(FFZT > 0 || HTZT != 2 ){ if (mainMenuArray1.count>0){
            RKTabItem *tabItem2 = [RKTabItem createUsualItemWithImageEnabled:nil imageDisabled:[UIImage imageNamed:@"message_add_background_highlighted"]];
            tabItem2.titleString = @"新增";
            tabItem2.titleFont = [UIFont systemFontOfSize:12];
            [tabItem2 addTarget:self selector:@selector(createSelector:)];
            [tabItems addObject:tabItem2];
        } else {
            RKTabItem *tabItem2 = [RKTabItem createUsualItemWithImageEnabled:nil imageDisabled:[UIImage imageNamed:@"message_add_background"]];
            tabItem2.titleString = @"新增";
            tabItem2.titleFont = [UIFont systemFontOfSize:12];
            [tabItems addObject:tabItem2];
        }}
        
        //分发按钮
        NSArray *mainMenuArray2 = [ModuleAuthorityEntity MR_findByAttribute:@"permissionsMark" withValue:@"P_HTGL_HTFF"];
        if(FFZT <= 0 && HTZT == 2){ if (mainMenuArray2.count>0){
            RKTabItem *tabItem2 = [RKTabItem createUsualItemWithImageEnabled:nil imageDisabled:[UIImage imageNamed:@"message_emotion_background_highlighted"]];
            tabItem2.titleString = @"分发";
            tabItem2.titleFont = [UIFont systemFontOfSize:12];
            [tabItem2 addTarget:self selector:@selector(distributeSelector:)];
            [tabItems addObject:tabItem2];
        } else {
            RKTabItem *tabItem2 = [RKTabItem createUsualItemWithImageEnabled:nil imageDisabled:[UIImage imageNamed:@"message_emotion_background"]];
            tabItem2.titleString = @"分发";
            tabItem2.titleFont = [UIFont systemFontOfSize:12];
            [tabItems addObject:tabItem2];
        }}
        
        RKTabView *titledTabsView = [[RKTabView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 48)];
        titledTabsView.titlesFontColor = [UIColor grayColor];
        titledTabsView.tabItems = tabItems;
        titledTabsView.drawSplitLine = YES;
        titledTabsView.backgroundColor = [UIColor whiteColor];
        [cell.contentView addSubview:titledTabsView];
        
        //添加分割线
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 0.5)];
        lineView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.1];
        [cell.contentView addSubview:lineView];
        
        return cell;
    }
    
    //合同审核
    if (indexPath.section == 2 && indexPath.row == 0) {
        NSString *identifier = [NSString stringWithFormat:@"OrderAuditTableViewCell%ld",(long)indexPath.section];
        AutoTextTableViewCell *cell = [[AutoTextTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell setDataArray:auditArray];
        return cell;
    }
    
    //合同授权与分发
    if (indexPath.section == 3 && indexPath.row == 0) {
        NSString *identifier = [NSString stringWithFormat:@"OrderOperateTableViewCell%ld",(long)indexPath.section];
        AutoTextTableViewCell *cell = [[AutoTextTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell setDataArray:operateArray];
        return cell;
    }
    
    if(indexPath.section == 4){
        //其他功能按钮
        NSString *identifierOne = [NSString stringWithFormat:@"TableOneButtonViewCellHT%ld=%ld",(long)indexPath.section,indexPath.row];
        TableOneButtonViewCell *cellOne = [tableView dequeueReusableCellWithIdentifier:identifierOne];
        if (cellOne == nil) {
            cellOne = [[TableOneButtonViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifierOne];
            cellOne.selectionStyle = UITableViewCellSelectionStyleDefault;
            cellOne.iconImage.image = [UIImage imageNamed:@"logistics_info_bus_icon"];
        }
        
        //绘制分割线
        if(indexPath.row != 0){
            UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(54, 0, SuperWidth - 54, 0.5)];
            lineView.backgroundColor = [UIColor colorWithWhite:0.1 alpha:0.15];
            [cellOne.contentView addSubview:lineView];
        }
        
        NSArray *valueArray = [self.functionArray objectAtIndex:indexPath.row];
        cellOne.titleLable.textColor = [UIColor darkGrayColor];
        cellOne.titleLable.text = valueArray[0];
        cellOne.explainLable.text = valueArray[1];
        
        return cellOne;
    }
    
    return nil;
}

#pragma mark
#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 30)];
    view.backgroundColor = [UIColor whiteColor];
    
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(8, 0, SuperWidth - 10, 29.5)];
    lable.textColor = ThemeColorBlue;
    lable.font = [UIFont boldSystemFontOfSize:15];
    
    if (section  == 0) {
        lable.text = @"合同进度分析";
    } else if(section == 1){
        lable.text = @"合同基本信息";
    } else if(section == 2){
        lable.text = @"合同审核信息";
    } else if(section == 3){
        lable.text = @"合同授权与分发";
    } else if(section == 4){
        lable.text = @"合同更多信息";
    }
    [view addSubview:lable];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 29.5, SuperWidth, 0.5)];
    lineView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.1];
    [view addSubview:lineView];
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 15;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0 && indexPath.row == 0) {
        return 235;
        
    } else if(indexPath.section == 0 && indexPath.row == 1) {
        return 48;
        
    } else if(indexPath.section == 1 && indexPath.row == 0) {
        AutoTextTableViewCell *cell = [[AutoTextTableViewCell alloc] init];
        [cell setDataArray:concreteArray];
        return cell.contentView.frame.size.height;
        
    } else if(indexPath.section == 2 && indexPath.row == 0) {
        AutoTextTableViewCell *cell = [[AutoTextTableViewCell alloc] init];
        [cell setDataArray:auditArray];
        return cell.contentView.frame.size.height;
        
    } else if(indexPath.section == 3 && indexPath.row == 0) {
        AutoTextTableViewCell *cell = [[AutoTextTableViewCell alloc] init];
        [cell setDataArray:operateArray];
        return cell.contentView.frame.size.height;

    }
    
    return 50;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSString *HTID = [self.orderInfo objectFormatStringForKey:@"合同ID"];
    
    NSArray *arrayValue = [self.functionArray objectAtIndex:indexPath.row];
    //NSInteger selectIndex = [arrayValue[2] integerValue];
    
    if(indexPath.section == 4 && indexPath.row == 0){
        //合同工程
        MTCContractProjectViewController *viewController = [[MTCContractProjectViewController alloc] initWithValue:self.orderInfo];
        [self.navigationController pushViewController:viewController animated:YES];
        
    } else if(indexPath.section == 4 && indexPath.row == 1){
        //方量追加
        MTCAlreadyAddConcreteViewController *viewController = [[MTCAlreadyAddConcreteViewController alloc] initWithValue:HTID];
        [self.navigationController pushViewController:viewController animated:YES];
        
    } else if(indexPath.section == 4 && indexPath.row == 2){
        //砼价格选项
        MTCConcretePriceViewController *viewController = [[MTCConcretePriceViewController alloc] initWithValue:HTID];
        [self.navigationController pushViewController:viewController animated:YES];
        
    }
}

#pragma mark -
#pragma mark Button Event

//合同授权、终止
- (void)accreditSelector:(id)sender
{
    CGFloat HTZT = [[self.orderInfo objectFormatFloatNumberForKey:@"Status"] floatValue];//合同状态
    if(HTZT == 1 || HTZT == 3){ //待授权、终止状态
        JGActionSheet *simple = [JGActionSheet actionSheetWithSections:@[[JGActionSheetSection sectionWithTitle:@"合同启用" message:@"合同启用后将允许分发到各站，确认启用该合同吗？" buttonTitles:@[@"启用"] buttonStyle:JGActionSheetButtonStyleRed], [JGActionSheetSection sectionWithTitle:nil message:nil buttonTitles:@[@"取消"] buttonStyle:JGActionSheetButtonStyleCancel]]];
        [simple setButtonPressedBlock:^(JGActionSheet *sheet, NSIndexPath *indexPath) {
            [sheet dismissAnimated:YES];
            //合同授权
            if (indexPath.section == 0 && indexPath.row == 0) {
                [self authorizationAndStopNetWorkContractData];
            }
        }];
        [simple showInView:self.navigationController.view animated:YES];
        
    } else if(HTZT == 2) { //已授权状态
        JGActionSheet *simple = [JGActionSheet actionSheetWithSections:@[[JGActionSheetSection sectionWithTitle:@"合同停用" message:@"合同停用后，该合同失效且不可生产，确认停用该合同吗？" buttonTitles:@[@"停用"] buttonStyle:JGActionSheetButtonStyleRed], [JGActionSheetSection sectionWithTitle:nil message:nil buttonTitles:@[@"取消"] buttonStyle:JGActionSheetButtonStyleCancel]]];
        [simple setButtonPressedBlock:^(JGActionSheet *sheet, NSIndexPath *indexPath) {
            [sheet dismissAnimated:YES];
            //合同终止
            if (indexPath.section == 0 && indexPath.row == 0) {
                [self authorizationAndStopNetWorkContractData];
            }
        }];
        [simple showInView:self.navigationController.view animated:YES];
    }
    
}

//新增合同
- (void)createSelector:(id)sender
{
    NSArray *menuArray = [ModuleAuthorityEntity MR_findByAttribute:@"permissionsMark" withValue:@"P_HTGL_HTXZ"];
    if(menuArray.count > 0) {
        MTCCreateContractViewController *view = [[MTCCreateContractViewController alloc] init];
        [self.navigationController pushViewController:view animated:YES];
    } else {
        [self showErrorHUDText:@"无操作权限" dismissAfterDelay:0];
    }

}

//分发合同
- (void)distributeSelector:(id)sender
{
    [self distributeStionNetWorkContractData];
}

//合同审核
- (void)checkSelector:(id)sender
{
    JGActionSheet *simple = [JGActionSheet actionSheetWithSections:@[[JGActionSheetSection sectionWithTitle:@"合同审核" message:@"合同通过审核后，将无法修改和删除该合同，确认通过合同审核吗？" buttonTitles:@[@"通过"] buttonStyle:JGActionSheetButtonStyleRed], [JGActionSheetSection sectionWithTitle:nil message:nil buttonTitles:@[@"取消"] buttonStyle:JGActionSheetButtonStyleCancel]]];
    [simple setButtonPressedBlock:^(JGActionSheet *sheet, NSIndexPath *indexPath) {
        [sheet dismissAnimated:YES];
        //审核合同
        if (indexPath.section == 0 && indexPath.row == 0) {
            [self checkNetWorkContractData];
        }
    }];
    [simple showInView:self.navigationController.view animated:YES];
}

//合同修改
- (void)modifySelector:(id)sender
{
    NSArray *menuArray = [ModuleAuthorityEntity MR_findByAttribute:@"permissionsMark" withValue:@"P_HTGL_HTXZ"];
    if(menuArray.count > 0) {
        //天元定制-修改
        NSArray *menuArray = [ModuleAuthorityEntity MR_findByAttribute:@"permissionsMark" withValue:@"P_HTGL_HTXZ_ZDXZ"];
        if(menuArray.count > 0) {
            MTCCreateContractTYDZController *view = [[MTCCreateContractTYDZController alloc] initWithValue:self.orderInfo];
            [self.navigationController pushViewController:view animated:YES];
            return;
        }
        //通用-修改
        MTCCreateContractViewController *view = [[MTCCreateContractViewController alloc] initWithValue:self.orderInfo];
        [self.navigationController pushViewController:view animated:YES];
        
    } else {
        [self showErrorHUDText:@"无操作权限" dismissAfterDelay:0];
    }
}

#pragma mark -
#pragma mark 网络获取分发站点

- (void)distributeStionNetWorkContractData
{
    JGProgressHUD *HUD = [self showSimpleHUDText:@"获取站点中"];
    
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeGroup];
    [content setModuleType:@"HTGL_JCXX_LIST"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    [content addParameterKey:@"Type" value:@3];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        [HUD dismissAnimated:YES];//关闭进度框
        
        //添加数据，刷新页面
        NSArray *firstArray = nil;
        if(result.resultArray && result.resultArray.count>0)
            firstArray = [result.resultArray firstObject];
        
        //数据处理
        if(firstArray && firstArray.count>0){
            [self distributeActionSheetStionHandle:firstArray];
        } else {
            [self showErrorHUDText:@"无分发站点"];
        }
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [HUD dismissAnimated:YES];//关闭进度框
        [self showErrorHUDText:@"获取失败"];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [HUD dismissAnimated:YES];//关闭进度框
        [self showErrorHUDText:@"网络异常"];
        
    }];
}

//分发合同弹出框
- (void)distributeActionSheetStionHandle:(NSArray*)stationArray
{
    NSMutableArray *sortByItemsArray = [[NSMutableArray alloc] init];
    for(int i=0;i<stationArray.count;i++){
        NSDictionary *mDictionary = [stationArray objectAtIndex:i];
        [sortByItemsArray addObject:[mDictionary objectFormatStringForKey:@"U_Name"]];
    }
    
    CGFloat height = sortByItemsArray.count * 44;
    BGRadioView *radioViewSortBy = [[BGRadioView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth - 40, height)];
    radioViewSortBy.rowItems =  sortByItemsArray;
    radioViewSortBy.maxRow = [sortByItemsArray count];
    radioViewSortBy.isMultiSelect = YES;
    
    JGActionSheetSection *sheetSection = [JGActionSheetSection sectionWithTitle:@"合同分发" message:@"提示：合同分发后将会自动下发到各站，\n请谨慎操作。请选择分发的站点(可多选)：" buttonTitles:@[@"分发"] buttonStyle:JGActionSheetButtonStyleDefault contentView:radioViewSortBy];
    
    JGActionSheetSection *sheetSectionCancel = [JGActionSheetSection sectionWithTitle:nil message:nil buttonTitles:@[@"取消"] buttonStyle:JGActionSheetButtonStyleCancel];
    
    JGActionSheet *simple = [JGActionSheet actionSheetWithSections:@[sheetSection, sheetSectionCancel]];
    [simple setButtonPressedBlock:^(JGActionSheet *sheet, NSIndexPath *indexPath) {
        //合同分发
        if (indexPath.section == 0 && indexPath.row == 0) {
            NSInteger dataCount = radioViewSortBy.selectArray.count;
            if (dataCount <= 0) return; //未选择任何数据
            //多个数据汇合整理
            NSMutableString *StationIDs = [NSMutableString string];
            for (int i=0; i<dataCount;i++) {
                NSNumber *select = [radioViewSortBy.selectArray objectAtIndex:i];
                NSDictionary *mDictionary = [stationArray objectAtIndex:[select integerValue]];
                NSString *StationID = [mDictionary objectFormatStringForKey:@"Code"];
                [StationIDs appendFormat:@"%@%@", StationID, (i < dataCount - 1 ? @",": @"")];
            }
            //连接网络，提交分发
            [self distributeNetWorkContractData:StationIDs];
        }
        [sheet dismissAnimated:YES];
    }];
    [simple showInView:self.navigationController.view animated:YES];
    
    //多选择回执
    [radioViewSortBy setSelectMultiBlock:^(NSMutableArray *array) {
        if(array && array.count > 0)
        [sheetSection setButtonStyle:JGActionSheetButtonStyleRed forButtonAtIndex:0];
        else [sheetSection setButtonStyle:JGActionSheetButtonStyleDefault forButtonAtIndex:0];
    }];
}

#pragma mark -
#pragma mark 网络处理

//网络合同审核
- (void)checkNetWorkContractData
{
    //获取用户登录信息
    UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
    NSString *HTBH = [self.orderInfo objectFormatStringForKey:@"合同编号"];
    JGProgressHUD *HUD = [self showSimpleHUDText:@"正在审核"];
    
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeGroup];
    [content setModuleType:@"HTGL_HTSH"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    
    [content addParameterKey:@"合同编号" value:HTBH];
    [content addParameterKey:@"审核人员" value:userInfo.username];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        [HUD dismissAnimated:YES];//关闭进度框
        //添加数据，刷新页面
        NSArray *firstArray = nil;
        if(result.resultArray && result.resultArray.count>0)
            firstArray = [result.resultArray firstObject];
        
        //数据处理
        if(firstArray && firstArray.count>0){
            [self showSuccessHUDText:@"审核成功"];
            NSDictionary *resultDic = [firstArray firstObject];
            NSDictionary *originalDic = [NSDictionary dictionaryWithDictionary:self.orderInfo];
            
            [self.orderInfo setValue:[resultDic objectFormatStringForKey:@"审核人员"] forKey:@"审核人员"];
            [self.orderInfo setValue:[resultDic objectFormatStringForKey:@"审核日期"] forKey:@"审核日期"];
            [self.orderInfo setValue:[resultDic objectFormatStringForKey:@"审核状态"] forKey:@"审核状态"];
            [self.orderInfo setValue:[resultDic objectFormatFloatNumberForKey:@"Confirm"] forKey:@"Confirm"];
            
            [self getOrderAllOrders:self.orderInfo];
            [self.tableView reloadData];
            
            NSArray *resultArray = @[originalDic,self.orderInfo];
            if(self.backResultDelagate) [self.backResultDelagate backResultDataKey:@"Check" dataValue:resultArray];
        } else {
            [self showErrorHUDText:@"审核失败"];
        }
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [HUD dismissAnimated:YES];//关闭进度框
        [self showErrorHUDText:@"审核失败"];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [HUD dismissAnimated:YES];//关闭进度框
        [self showErrorHUDText:@"网络异常"];
        
    }];
    
}

//网络合同授权和终止
- (void)authorizationAndStopNetWorkContractData
{
    CGFloat HTZT = [[self.orderInfo objectFormatFloatNumberForKey:@"Status"] floatValue];//合同状态
    NSString *HTBH = [self.orderInfo objectFormatStringForKey:@"合同编号"];//合同状态
    
    NSString *keyString = nil;
    NSString *promptString = nil;
    NSString *valueString = nil;
    if (HTZT == 1 || HTZT == 3) { //待授权、终止状态，进行授权操作
        promptString = @"启用";
        valueString = @"2";
        keyString = @"AuthContract";
        
    } else if(HTZT == 2) { //已授权状态，进行终止操作
        promptString = @"停用";
        valueString = @"3";
        keyString = @"StopContract";
    }
    
    JGProgressHUD *HUD = [self showSimpleHUDText:[NSString stringWithFormat:@"正在%@中",promptString]];
    
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeGroup];
    [content setModuleType:@"HTGL_HTSQ"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    
    [content addParameterKey:@"合同编号" value:HTBH];
    [content addParameterKey:@"合同状态" value:valueString];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        [HUD dismissAnimated:YES];//关闭进度框
        
        //添加数据，刷新页面
        NSArray *firstArray = nil;
        if(result.resultArray && result.resultArray.count>0)
            firstArray = [result.resultArray firstObject];
        
        //数据处理
        if(firstArray && firstArray.count>0){
            [self showSuccessHUDText:[NSString stringWithFormat:@"%@成功",promptString]];
            NSDictionary *resultDic = [firstArray firstObject];
            NSDictionary *originalDic = [NSDictionary dictionaryWithDictionary:self.orderInfo];
            
            [self.orderInfo setValue:[resultDic objectFormatStringForKey:@"合同状态"] forKey:@"合同状态"];
            [self.orderInfo setValue:[resultDic objectFormatFloatNumberForKey:@"Status"] forKey:@"Status"];
            
            [self getOrderAllOrders:self.orderInfo];
            [self.tableView reloadData];
            NSArray *resultArray = @[originalDic,self.orderInfo];
            if(self.backResultDelagate) [self.backResultDelagate backResultDataKey:keyString dataValue:resultArray];
            
        } else {
            [self showErrorHUDText:[NSString stringWithFormat:@"%@失败",promptString]];
        }
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [HUD dismissAnimated:YES];//关闭进度框
        [self showErrorHUDText:[NSString stringWithFormat:@"%@失败",promptString]];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [HUD dismissAnimated:YES];//关闭进度框
        [self showErrorHUDText:@"网络异常"];
    }];
}

//网络合同分发
- (void)distributeNetWorkContractData:(NSString*)stationID
{
    //获取用户登录信息
    NSString *HTBH = [self.orderInfo objectFormatStringForKey:@"合同编号"];//合同状态
    JGProgressHUD *HUD = [self showSimpleHUDText:@"正在分发"];
    
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeGroup];
    [content setModuleType:@"HTGL_HTFF"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    
    [content addParameterKey:@"合同编号" value:HTBH];
    [content addParameterKey:@"站点" value:stationID];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        [HUD dismissAnimated:YES];//关闭进度框
        
        //添加数据，刷新页面
        NSArray *firstArray = nil;
        if(result.resultArray && result.resultArray.count>0)
            firstArray = [result.resultArray firstObject];
        
        //数据处理
        if(firstArray && firstArray.count>0){
            [self showSuccessHUDText:@"分发成功"];
            NSDictionary *resultDic = [firstArray firstObject];
            NSDictionary *originalDic = [NSDictionary dictionaryWithDictionary:self.orderInfo];
            
            [self.orderInfo setValue:[resultDic objectFormatFloatNumberForKey:@"FFZT"] forKey:@"FFZT"];
            [self.orderInfo setValue:[resultDic objectFormatStringForKey:@"分发状态"] forKey:@"分发状态"];
            
            [self getOrderAllOrders:self.orderInfo];
            [self.tableView reloadData];
            
            NSArray *resultArray = @[originalDic,self.orderInfo];
            if(self.backResultDelagate) [self.backResultDelagate backResultDataKey:@"Distribute" dataValue:resultArray];
        } else {
            [self showErrorHUDText:@"分发失败"];
        }
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [HUD dismissAnimated:YES];//关闭进度框
        [self showErrorHUDText:@"分发失败"];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [HUD dismissAnimated:YES];//关闭进度框
        [self showErrorHUDText:@"网络异常"];
        
    }];
}

#pragma mark -
#pragma mark BackResultDataDelagate

- (void) backResultDataKey:(id)key dataValue:(id)backValue
{
    //合同修改成功处理
    if (key && backValue && [key isEqualToString:@"ModifSuccess"]) {
        NSMutableDictionary *backDictionary = backValue;
        NSDictionary *originalDic = [NSDictionary dictionaryWithDictionary:self.orderInfo];
        self.orderInfo = backDictionary;
        
        [self getOrderAllOrders:self.orderInfo];
        [self.tableView reloadData];
        
        NSArray *resultArray = @[originalDic,self.orderInfo];
        if(self.backResultDelagate) [self.backResultDelagate backResultDataKey:@"Modif" dataValue:resultArray];
    }
}

@end

